<template>
  <Editor
    tinymce-script-src="/tinymce/tinymce.min.js"
    :init="init"
    v-model="content"
    license-key="gpl"
  />
</template>
<script setup lang="ts">
import { uploadApi } from "@/apis/upload";
import Editor from "@tinymce/tinymce-vue";

const props = defineProps({
  content: {
    type: String,
    default: "",
  },
});

watch(
  () => props.content,
  (newContent) => {
    content.value = newContent;
  }
);

const content = ref("");

const emit = defineEmits(["editorChange", "resetForm"]);

function editorChange() {
  emit("editorChange", content);
}

async function upload(blobInfo: any /* , progress: any */) {
  const formData = new FormData();
  formData.append("file", blobInfo.blob());
  try {
    const res: any = await uploadApi(formData);
    if (res.code === 0) {
      return res.data;
    } else {
      throw new Error("上传失败: " + res.message);
    }
  } catch (error: any) {
    throw new Error("上传失败: " + (error.message || error));
  }
}

watch(content, () => {
  editorChange();
});

const init = {
  language: "zh_CN",
  language_url: "/tinymce/langs/zh_CN.js",
  placeholder: "请输入内容...",
  height: 500,
  width: "100%",
  branding: false,
  promotion: false,
  highlight_on_focus: false,
  images_upload_handler: upload,
  plugins: [
    "advlist",
    "autolink",
    "lists",
    "link",
    "image",
    "charmap",
    "preview",
    "anchor",
    "searchreplace",
    "visualblocks",
    "code",
    "fullscreen",
    "insertdatetime",
    "media",
    "table",
    "code",
    "help",
    "wordcount",
  ],
  toolbar:
    "undo redo | styles | " +
    "bold italic forecolor | alignleft aligncenter " +
    "alignright alignjustify | bullist numlist outdent indent | " +
    "removeformat | help",
  content_style:
    "body { font-family:Helvetica,Arial,sans-serif; font-size:14px }",
};
</script>
